package com.leostadyn.stackfarm.timestatistics.view.activity.admin.staff;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.leostadyn.stackfarm.timestatistics.R;
import com.leostadyn.stackfarm.timestatistics.base.BaseActivity;
import com.leostadyn.stackfarm.timestatistics.model.bean.AddStaffBean;
import com.leostadyn.stackfarm.timestatistics.model.bean.JobBean;
import com.leostadyn.stackfarm.timestatistics.model.bean.PostBean;
import com.leostadyn.stackfarm.timestatistics.model.bean.UserBean;
import com.leostadyn.stackfarm.timestatistics.net.api.AdminApi;
import com.leostadyn.stackfarm.timestatistics.net.base.OriginalSubscriber;
import com.leostadyn.stackfarm.timestatistics.net.base.ResponseThrowable;
import com.leostadyn.stackfarm.timestatistics.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StaffAddActivity extends BaseActivity implements View.OnClickListener {

    TextView title;
    EditText name;
    TextView job;
    EditText user_name;
    EditText password;
    EditText confirm_password;
    Button btn_add;
    UserBean userBean;
    private String mIndex = "-1";
    private int GROUP = 100;
    String post;
    private List<PostBean> listdata = new ArrayList<>();
    private List<JobBean> jobBeanList = new ArrayList<>();
    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            checkButton();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staff_add);
        post = getIntent().getStringExtra("job");
        initView();
    }

    public void initView() {
        title = findViewById(R.id.nav_txt_title);
        title.setText("添加人员");

        findViewById(R.id.nav_img_back).setOnClickListener(v -> {
            finish();
        });

        name = findViewById(R.id.satff_add_edt_name);
        job = findViewById(R.id.staff_add_select_job);
        user_name = findViewById(R.id.staff_add_et_username);
        password = findViewById(R.id.staff_add_input_pwd);
        confirm_password = findViewById(R.id.staff_add_confirm_pwd);
        btn_add = findViewById(R.id.staff_add_btn_confirm);

        name.addTextChangedListener(mTextWatcher);
        job.addTextChangedListener(mTextWatcher);
        user_name.addTextChangedListener(mTextWatcher);
        password.addTextChangedListener(mTextWatcher);
        confirm_password.addTextChangedListener(mTextWatcher);

        btn_add.setOnClickListener(this);


    }

    public void onSelectJob(View v) {
        startActivityForResult(new Intent(this, JobListActivity.class).putExtra("mIndex", mIndex), GROUP);

    }

    public void getIndex(String post) {
        HashMap<String, String> queryMap = new HashMap<>();
        AdminApi.getInstance().getJob().subscribe(new OriginalSubscriber<List<JobBean>>(compositeDisposable) {

            @Override
            public void onError(ResponseThrowable e) {

            }

            @Override
            public void onNext(List<JobBean> jobBeans, String msg) {
                jobBeanList = jobBeans;
                if (jobBeanList != null && jobBeanList.size() > 0) {
                    for (JobBean job : jobBeanList) {
                        queryMap.put(job.getName(), job.getId());
                    }
                    mIndex = queryMap.get(post);
                }

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (GROUP == requestCode) {
                if (data != null) {
                    //mIndex = data.getStringExtra("mIndex");
                    String info = data.getStringExtra("info");
                    getIndex(info);
                    job.setText(info + ">");
                }
            }
        }
    }

    boolean checkUserTextLength() {
        int accountLength = user_name.getText().toString().length();
        return accountLength < 30;
    }

    boolean checkPasswordTextLength() {

        int passwordLength = password.getText().toString().length();

        return passwordLength >= 6 && passwordLength <= 16;
    }

    private void checkButton() {

        if (isFill()) {
            btn_add.setEnabled(true);
        } else {
            btn_add.setEnabled(false);
        }

    }

    public boolean isFill() {
        String staff_edit_id = name.getText().toString().trim();
        if (TextUtils.isEmpty(staff_edit_id)) {
            return false;
        }

        String staff_edit_user_name = user_name.getText().toString().trim();
        if (TextUtils.isEmpty(staff_edit_user_name)) {
            return false;
        }

        String satff_edit_job = job.getText().toString().trim();
        if (TextUtils.isEmpty(satff_edit_job)) {
            return false;
        }
        String pd = password.getText().toString().trim();
        String pd1 = confirm_password.getText().toString().trim();
        return !TextUtils.isEmpty(pd) && !TextUtils.isEmpty(pd1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.staff_add_btn_confirm:
                String newPassword = password.getText().toString().trim();
                String confirm_password = this.confirm_password.getText().toString().trim();
                if (!checkUserTextLength()) {
                    ToastUtil.show(StaffAddActivity.this, "用户名超过限制");
                    return;
                } else {

                    if (!checkPasswordTextLength()) {
                        ToastUtil.show(StaffAddActivity.this, "请输入6~16位密码");
                        return;
                    } else if (!newPassword.equals(confirm_password)) {
                        ToastUtil.show(StaffAddActivity.this, "密码不一致");
                        return;
                    }
                    addStaff();
                }
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkButton();
    }

    public void addStaff() {
        String staffName = name.getText().toString().trim();
        String staffJob = job.getText().toString().trim();
        String staffUsername = user_name.getText().toString().trim();
        String staffPassWord = password.getText().toString().trim();
        String staffConPdw = confirm_password.getText().toString().trim();

        HashMap<String, String> map = new HashMap<String, String>();
        /*if (userBean == null && TextUtils.isEmpty(userBean.getToken())) {
            userBean = (UserBean) SaveObjectTools.INSTANCE().getObjectData(Constants.USERINFO);
        }*/
        map.put("name", staffName);
        map.put("password", staffConPdw);
        map.put("postId", mIndex);
        map.put("userName", staffUsername);

        /* headers.put("access-token", userBean.getToken());*/

        final KProgressHUD dialog = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setCancellable(true).setAnimationSpeed(2).setDimAmount(0.5f);
        dialog.show();
        AdminApi.getInstance().addStaff(map).subscribe(new OriginalSubscriber<AddStaffBean>(compositeDisposable) {
            @Override
            public void onError(ResponseThrowable e) {
                dialog.dismiss();
                ToastUtil.show(StaffAddActivity.this, e.getMsg());
            }

            @Override
            public void onNext(AddStaffBean addDutyDataBean, String msg) {
                dialog.dismiss();
                ToastUtil.show(StaffAddActivity.this, "添加成功");
                Intent intent = new Intent();
                intent.putExtra("success", 1);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

}
